﻿using System;
using System.Collections.Generic;
using System.Linq;
using Max.Domain.Mapping;
using Ordering.BusinessLayer;
using System.ServiceModel;
using Max.Domain.Mapping.Entity;

namespace Ordering.Service.Application
{
    public class OrderingService : IOrderingService
    {
        public IList<Contract.CustomerItem> ListAllCustomers()
        {
            using (var context = new OrderingContext())
            {
                var result = context.Customers;

                return new Mapper().MapToCustomerItemCollection(result);
            }
        }

        public IList<Contract.OrderItem> ListOrdersOfCustomer(int customerId)
        {
            using (var context = new OrderingContext())
            {
                var result = context.Orders.Where(o => o.CustomerId == customerId);

                return new Mapper().MapToOrderItemCollection(result);
            }
        }

        public Contract.OrderDetail GetDetailedOrder(int orderNumber)
        {
            using (var context = new OrderingContext())
            {
                var result = context.Orders.SingleOrDefault(o => o.Id == orderNumber);

                return new Mapper().MapToOrderDetail(result);
            }
        }

        [OperationBehavior(TransactionScopeRequired = true)]
        public int SaveOrder(Contract.OrderDetail newOrEditedOrder)
        {
            using (var context = new OrderingContext())
            {
                var order = new ReverseMapper(new EntityModelObjectSource(context))
                    .AllowCreatingAndUpdating<Order>()
                    .AllowCreatingAndUpdating<OrderLine>()
                    .MapFromOrderDetail(newOrEditedOrder);

                context.SaveChanges();

                return order.Id;
            }
        }
    }
}